<template>
	<view class="content">
		<view class="TabView">
			<view class="TabView_item">
				<text :class="swiperIndex == 0?'Title1':'Title2'" @click="toDetection()">监测</text>
				<view :class="swiperIndex == 0?'TabsLine1':'TabsLine2'"></view>
			</view>
			<view class="TabView_item">
				<text :class="swiperIndex == 1?'Title1':'Title2'" @click="toTrend()">趋势</text>
				<view :class="swiperIndex == 1?'TabsLine1':'TabsLine2'"></view>
			</view>
		</view>

		<!-- swiper 切换 -->
		<view class="swiperView">
			<swiper :indicator-dots="false" :autoplay="false" :interval="3000" :duration="400" :current="swiperIndex"
				@change="changeItem" style="height: 100%;">
				<swiper-item>
					<!-- 检测页内容 -->
					<view style="overflow: auto;height: 100%;">
						<view class="flex-c" style="width: 100%;height: 100%;">
							<!-- 无网络的提示 -->
							<image v-show="!isNet" class="NetState" :src="staticUrl + '/image/img_noNet.png'" mode="">
							</image>
							<view class="HeadBandImgView flex-c">
								<image :animation="animationData" :src="staticUrl + '/image/detection/headband.png'"
									mode="widthFix" class="HeadBandImg"></image>
							</view>
							<view id="detePage" class="absoultView flex-c">
								<view class="DisplayArea flex-c">
									<!-- 未连接状态 -->
									<view v-if="!isConnected" class="ConnectBtn flex-c" @click="toConnectBluetooth()">
										<text v-text="ConnectBtnText"></text>
									</view>
									<!-- 已连接状态  状态栏  显示-->
									<view v-else class="StatusBar">
										<view class="StatusBar_item"
											style="width:150rpx;padding: 5rpx;border-radius: 12px; background-color: #e7e7e7;"
											@click="disBleConnect()">
											<image :src="staticUrl + '/image/detection/icon_disConnect.png'"
												style="width: 46rpx;height: 42rpx;"></image>
											<text class="StatusBar_item_Des">断开连接</text>
										</view>
										<view style="width: 2rpx;height: 60rpx;background-color: #E6E6E6;"></view>
										<view class="StatusBar_item">
											<image v-if="adorn == '未佩戴'"
												:src="staticUrl + '/image/detection/notadorn.png'"
												style="width: 52rpx;height: 39rpx;"></image>
											<image v-else :src="staticUrl + '/image/detection/adorn.png'"
												style="width: 52rpx;height: 39rpx;"></image>
											<text v-if="adorn == '未佩戴'" class="StatusBar_item_Des noAdorn">未佩戴</text>
											<text v-else class="StatusBar_item_Des">已佩戴</text>
										</view>
										<view style="width: 2rpx;height: 60rpx;background-color: #E6E6E6;"></view>
										<view class="StatusBar_item">
											<text class="power">{{ power }}%</text>
											<text class="StatusBar_item_Des">头环电量</text>
										</view>
									</view>
								</view>
								<!-- 底部4个卡片区域 -->
								<image class="card_img" :src="staticUrl + '/image/detection/img_fastMonitor.png'"
									style="margin-top: 27rpx;width: 664rpx;height: 167rpx;" @click="toFastMonitor()">
								</image>
								<image class="card_img" :src="staticUrl + '/image/detection/img_deepMonitor.png'"
									style="width: 664rpx;height: 167rpx;" @click="toDeepMonitor()"></image>
								<view style="display: flex;">
									<image class="card_img" :src="staticUrl + '/image/detection/img_historyReport.png'"
										style="width: 320rpx;height: 255rpx;" @click="toHistoryReport()"></image>
									<image class="card_img" :src="staticUrl + '/image/detection/img_dataExplain.png'"
										style="margin-left: 24rpx; width: 320rpx;height: 255rpx;margin-bottom: 22rpx;"
										@click="toIntroductDetail()"></image>
								</view>
							</view>
						</view>
					</view>
				</swiper-item>
				<swiper-item>
					<!-- 趋势页内容 -->
					<view style="overflow: auto;height: 100%;">
						<view class="TendArea">
							<view v-if="!isHistoryData" style="margin-top: 300rpx;">
								<image :src="staticUrl + '/image/detection/img_nodata.png'"
									style="width: 424rpx;height: 409rpx;"></image>
							</view>
							<view v-if="isHistoryData" class="content">
								<view class="chartArea flex-c">
									<view class="selectDateView">
										<view class="selectDateBtn flex-c" :style="{ background: selectDateBtnBg1 }"
											@click="SelectDate(7)">7日</view>
										<view class="selectDateBtn flex-c" :style="{ background: selectDateBtnBg2 }"
											@click="SelectDate(15)">15日</view>
										<view class="selectDateBtn flex-c" :style="{ background: selectDateBtnBg3 }"
											@click="SelectDate(30)">30日</view>
										<view class="selectDateBtn flex-c" :style="{ background: selectDateBtnBg4 }"
											@click="SelectDate(60)">60日</view>
									</view>
									<!-- 柱状图 区域 -->
									<view class="charts-box" @touchmove.stop.prevent="moveHandle">
										<qiun-data-charts type="column" :chartData="chartData" :errorReload="false"
											:echartsH5="false" :echartsApp="false" background="none" :tapLegend="false"
											:ontouch="true" :canvas2d="true" canvasId="wsx" @getIndex="getChartIndex" />
									</view>
								</view>
								<view class="reportDataView">
									<image class="reportDataViewImg"
										:src="staticUrl + '/image/detection/icon_trendTip.png'" mode="widthFix"></image>
									<view class="reportDataView_T" style="margin-top: 100rpx;">
										<view class="reportData_top" style="margin-left: 50rpx;">
											<text>健康检测:</text>
											<text>{{healthyCount}}</text>
											<text>次</text>
										</view>
										<view class="reportData_top" style="margin-right: 50rpx;">
											<text>心率:</text>
											<text>{{trendReport.heartRate}}</text>
											<text>次/分</text>
										</view>
									</view>
									<view class="line"></view>
									<view class="reportDataView_T mt28">
										<view class="reportDataItem flex-c">
											<text class="reportDataItem_name">血管年龄</text>
											<view class="reportDataItem_des flex-c">{{trendReport.bloodAge}}</view>
										</view>
										<view class="reportDataItem flex-c">
											<text class="reportDataItem_name">血流波动</text>
											<view class="reportDataItem_des flex-c">{{trendReport.headhealth}}</view>
										</view>
										<view class="reportDataItem flex-c">
											<text class="reportDataItem_name">血管弹性</text>
											<view class="reportDataItem_des flex-c">{{trendReport.bloodElasticity}}
											</view>
										</view>
										<view class="reportDataItem flex-c">
											<text class="reportDataItem_name">调节能力</text>
											<view class="reportDataItem_des flex-c">{{trendReport.bloodAdjust}}</view>
										</view>
									</view>
								</view>
								<view style="display: none;">
									<!--  生活建议 饮食建议 -->
									<view class="LifeAdvice mt45">
										<view class="tipView">
											<view class="tipLine ml28" style="background-color: #1BC91A;"></view>
											<text class="LifeAdvice_title" style="margin-left: 18rpx;">生活建议</text>
										</view>
										<view class="mt45" style="margin-left: 56rpx;">
											<text
												class="LifeAdvice_content">{{ lifeAdvice.description.slice(0,55) }}...</text>
											<text class="LookDetailText" @click="toLifeDetail()">查看详情</text>
										</view>
									</view>

									<view class="LifeAdvice mt45">
										<view class="tipView">
											<view class="tipLine ml28"></view>
											<text class="LifeAdvice_title" style="margin-left: 18rpx;">饮食建议</text>
										</view>
										<view class="mt45" style="margin-left: 56rpx;">
											<text
												class="LifeAdvice_content">{{dietAdvice.description.slice(0,55)}}...</text>
											<text class="LookDetailText" @click="toDietDetail()">查看详情</text>
										</view>
									</view>

									<!-- 饮食建议 -->
									<view class="card3">
										<view class="card3_item1">
											<view class="card3_item1_time flex-c">
												<text class="card3_item1_time_T1">早餐</text>
												<text class="card3_item1_time_T2">ZAO CAN</text>
											</view>
											<view class="card3_item1_food flex-c ML33"
												v-for="(item, index) in breakfast" :key="index">
												<image :src="item.accessUrl"></image>
												<text>{{ item.description }}</text>
											</view>
										</view>
										<view class="card3_item1">
											<view class="card3_item1_time flex-c">
												<text class="card3_item1_time_T1">午餐</text>
												<text class="card3_item1_time_T2">WU CAN</text>
											</view>
											<view class="card3_item1_food flex-c ML33" v-for="(item, index) in lunch"
												:key="index">
												<image :src="item.accessUrl"></image>
												<text>{{ item.description }}</text>
											</view>
										</view>
										<view class="card3_item1">
											<view class="card3_item1_time flex-c">
												<text class="card3_item1_time_T1">晚餐</text>
												<text class="card3_item1_time_T2">WAN CAN</text>
											</view>
											<view class="card3_item1_food flex-c ML33" v-for="(item, index) in dinner"
												:key="index">
												<image :src="item.accessUrl"></image>
												<text>{{ item.description }}</text>
											</view>
										</view>
									</view>
									<!-- 菜谱 -->
									<view class="card_cookBook">
										<view class="card_cookBook_item" v-for="(item, index) in menu" :key="index">
											<image :src="item.image"></image>
											<view class="card_cookBook_item_R">
												<text class="card_cookBook_item_RT_text">{{ item.title }}</text>
												<view style="margin-top: 10rpx;">
													<text
														class="LifeAdvice_content">{{ item.description.slice(0, 20) }}...</text>
													<text class="LookDetailText"
														@click="toMenuDetail(index)">查看详情</text>
												</view>
											</view>
										</view>
									</view>
									<!-- 运动建议 -->
									<view class="LifeAdvice mt45">
										<view class="tipView">
											<view class="tipLine ml28"></view>
											<text class="LifeAdvice_title" style="margin-left: 18rpx;">运动建议</text>
										</view>
										<view class="mt45" style="margin-left: 56rpx;">
											<text
												class="LifeAdvice_content">{{sportAdvice.description.slice(0,55)}}...</text>
											<text class="LookDetailText" @click="toSportDetail()">查看详情</text>
										</view>
									</view>
									<scroll-view class="scroll-view_row" scroll-x="true" scroll-left="120"
										show-scrollbar="false">
										<view class="scroll-view_item" v-for="(item, index) in sportDetail" :key="index"
											@click="toSportCardDetail(index)">
											<image :src="item.image" mode=""></image>
											<view class="scroll-view_item_view">
												<text>{{ item.description.slice(0,15)}}</text>
											</view>
										</view>
									</scroll-view>
									<view class="card_bottom">
										<view class="card_bottom_L">
											<view
												style="width: 10rpx;height: 30rpx;background-color: #F5212D;border-radius: 50px;">
											</view>
											<text
												style="font-size: 40rpx;font-family: Source Han Sans CN;font-weight: bold;color: #000000;margin-left: 17rpx;">药膳</text>
											<view
												style="width: 5rpx;height: 37rpx;background-color: #000000;border-radius: 50px;margin-left: 17rpx;">
											</view>
											<text
												style="font-size: 38rpx;font-family: Source Han Sans CN;font-weight: normal;color: #000000;margin-left: 23rpx;">
												{{ tonicDiet.title }}
											</text>
										</view>
										<image :src="staticUrl + '/image/suggest/icon_look_red.png'"
											style="width: 130rpx;height: 53rpx;margin-right: 30rpx;"
											@click="toTonicDietDetail()"></image>
									</view>
								</view>
							</view>
						</view>
					</view>
				</swiper-item>
			</swiper>
		</view>
		<!-- 弹出层 -->
		<!-- 蓝牙适配器未开启 -->
		<uni-popup ref="popup1" :mask-click="false" :safe-area="false" type="dialog">
			<view class="popup1">
				<image class="icon_close" :src="staticUrl + '/image/icon_close.png'" @click="closePopup()"></image>
				<image class="icon_content" :src="staticUrl + '/image/detection/icon_bluetooth.png'"></image>
				<view class="flex-c">
					<text class="popup1Content">连接失败</text>
					<text class="popup1Content">未打开蓝牙开关</text>
				</view>
				<view class="popupBottomView flex-c" @click="tryOpBluetoothAdapter()"><text>我知道了</text></view>
			</view>
		</uni-popup>
		<!-- 头环未开机 没找到EI的设备 -->
		<uni-popup ref="popup2" :mask-click="false" :safe-area="false" type="dialog">
			<view class="popup1">
				<image class="icon_close" :src="staticUrl + '/image/icon_close.png'" @click="closePopup()"></image>
				<image class="icon_content" :src="staticUrl + '/image/detection/icon_open.png'"></image>
				<view class="flex-c">
					<text class="popup1Content">连接失败</text>
					<text class="popup1Content">检查头环是否开机</text>
				</view>
				<view class="popupBottomView flex-c" @click="IKnow()"><text>我知道了</text></view>
			</view>
		</uni-popup>

		<!-- 和头环连接中断 -->
		<uni-popup ref="popup3" :mask-click="false" :safe-area="false" type="dialog">
			<view class="popup1">
				<image class="icon_close" :src="staticUrl + '/image/icon_close.png'" @click="closePopup()"></image>
				<image class="icon_content" :src="staticUrl + '/image/detection/icon_open.png'"></image>
				<view class="flex-c">
					<text class="popup1Content">长时间未操作头环</text>
					<text class="popup1Content">{{belDeviceState}}</text>
				</view>
				<view class="popupBottomView flex-c" @click="IKnow1()"><text>我知道了</text></view>
			</view>
		</uni-popup>
		<!-- power low Warning -->
		<uni-popup ref="powerPopup" :mask-click="false" :safe-area="false" type="dialog">
			<view class="popup1">
				<image class="icon_close" :src="staticUrl + '/image/icon_close.png'" @click="closePopup()"></image>
				<image class="icon_content" :src="staticUrl + '/image/detection/icon_power.png'"></image>
				<view class="flex-c">
					<text class="popup1Content">头环电量低</text>
					<text class="popup1Content">请您及时充电</text>
				</view>
				<view class="popupBottomView flex-c" @click="IKnow2()"><text>我知道了</text></view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	const app = getApp();
	import store from '../../store/index.js';
	import * as api from '@/api/login';
	import util from '../../utils/utils.js';
	import {
		mapState
	} from 'vuex'; //引入mapState
	export default {
		data() {
			return {
				// 临时
				staticUrl: this.$config.StaticUrl,
				swiperIndex: 0, //...
				isToConnect: false, //是否去主动连接蓝牙
				ConnectBtnText: '连接头环', //连接按钮上的文字
				isClick: true, //按钮是否可以点击
				show: false, //是否弹出建模弹窗
				buffer: [], //从蓝牙接收来的原始数据
				power: 0, //电量
				adorn: '未佩戴', //头环是否佩戴情况
				isDevice: null, //是否有EI的设备
				isMonitor: false, //是否可以检测
				animationData: {}, //动画
				operationTimer: null, //未操作头环断开连接定时器
				belDeviceState: '连接已断开',
				deviceVersion: '', //固件版本
				// 趋势页变量
				selectDateBtnBg1: '#e5e5e5',
				selectDateBtnBg2: '',
				selectDateBtnBg3: '',
				selectDateBtnBg4: '',
				trendData: [], //存放趋势的数组，
				// 图表配置
				choiceTrendData: [],
				// padding:[10,10,10,100],
				chartData: {
					categories: [],
					series: [{
						name: '分数',
						data: []
					}]
				},
				SuggestContent: '',
				// 健康报告相关参数
				healthyCount: 0,
				healthyMax: 0,
				healthyMin: 0,
				healthyAvg: 0,
				isHistoryData: true, //是否有历史数据
				userId: '',
				keyWord: '', //关键词
				// 生活建议
				lifeAdvice: {
					description: '',
					accessUrl: ''
				},
				// 饮食建议
				dietAdvice: {
					description: '',
					accessUrl: ''
				},
				// 运动建议
				sportAdvice: {
					description: '',
					accessUrl: ''
				},
				// 运动详情
				sportDetail: [],
				// 药膳
				tonicDiet: {
					title: '',
					accessUrl: ''
				},
				// 早餐
				breakfast: {},
				lunch: {},
				dinner: {},
				// 菜谱
				menu: [],
				// move tab 滑动
				moveTab: {
					clientX: null,
					clientY: null,
					touchStartTime: null
				},
				trendReport: {
					heartRate: 0,
					bloodAge: '--',
					bloodAdjust: '--',
					bloodElasticity: '--',
					headhealth: '--'
				}
			};
		},
		// 引用 store中的变量
		computed: {
			...mapState({
				isNet: function(state) {
					return state.isNet;
				},
				originalData: function(state) {
					return state.originalData;
				},
				isConnected: function(state) {
					return state.isConnected;
				},
				isEiDevice: state => state.isEiDevice,
				isBluetoothAdapter: state => state.isBluetoothAdapter
			})
		},
		// 监听本地数据变化
		watch: {
			originalData: {
				handler(newName, oldName) {
          console.log('originalData', newName)
					// 在这里进行逻辑处理
					if (newName != [] || newName != null) {
						this.DealMessage(newName);
					}
				},
				immediate: true,
				deep: true
			},
			// 监听蓝牙适配器状态
			isBluetoothAdapter: {
				handler(newValue, oldValue) {
					console.log('适配器状态' + newValue);
					if (!newValue) {
						this.$refs.popup1.open('center');
					} else {
						this.$refs.popup1.close();
					}
				}
			},
			// 监听是否存在EI的设备
			isEiDevice: {
				handler(newValue, oldValue) {
					console.log('是否存在EI的设备');
					if (!newValue) {
						this.$refs.popup2.open('center');
					}
				}
			},
			// 监听蓝牙连接状态
			isConnected: {
				handler(newValue, oldValue) {
					console.log(newValue);
					if (!newValue) {
						if (!store.state.isActiveDisConnect) {
							app.deteDeviceState(true)
							let that = this
							uni.$once('ble-device-state', function(data) {
								that.belDeviceState = data.msg
								that.$refs.popup3.open('center')
								app.globalData.isDeteDeviceState = false
								app.closeBluetoothAdapter();
							})
						} else {
							this.$toast('您已断开连接')
							app.closeBluetoothAdapter();
						}
						this.isMonitor = false;
						this.ConnectBtnText = '连接设备';
						this.isClick = true;
						clearInterval(this.operationTimer)
						app.globalData.notOperatedCount = 0
					} else {
						this.$refs.popup3.close();
						this.isMonitor = true;
						store.commit('isActiveDisConnect', false)
						this.loopDete()
					}
				}
			}
		},
		onLoad() {
			this.userId = this.$store.state.userInfo.currentUser.userId;
			this.getUserModel();
			uni.showShareMenu({
				withShareTicket: true,
				menus: ['shareAppMessage']
			})
		},
		onShow() {
			var animation = uni.createAnimation({
				transformOrigin: '50% 50%',
				duration: 500,
				timingFunction: 'linear'
			});
			this.animation = animation;
			animation.scale(1.25, 1.25).step();
			this.animationData = animation.export();
			store.commit('isLoopCheckConnectState', true)
		},
		onHide() {
			this.animation = null;
		},
		methods: {
			// 授权开启蓝牙适配器
			tryOpBluetoothAdapter() {
				store.commit('BluetoothAdapterState', true);
				this.$refs.popup1.close();
				// this.$utils.requestOpenBluetooth();
				this.ConnectBtnText = '连接头环';
				this.isClick = true;
			},
			//循环检测是否操作头环（超时未操作则断开连接）
			loopDete() {
				let that = this
				that.operationTimer = setInterval(function() {
					if (app.globalData.notOperatedCount >= 25) {
						clearInterval(that.operationTimer)
						app.closeBLEConnection()
						app.globalData.notOperatedCount = 0
					} else {
						if (store.state.isLoopCheckConnectState && that.adorn == "未佩戴") {
							app.globalData.notOperatedCount++
						}
						if (that.adorn == '已佩戴') app.globalData.notOperatedCount = 0
					}
				}, 5000)
			},
			// 无设备的响应
			IKnow() {
				store.commit('isEiDevice', true);
				this.$refs.popup2.close();
				this.ConnectBtnText = '连接头环';
				this.isClick = true;
			},
			// 断开的响应
			IKnow1() {
				this.$refs.popup3.close();
				this.ConnectBtnText = '连接头环';
				this.isClick = true;
			},
			// 断开的响应
			IKnow2() {
				this.$refs.powerPopup.close();
			},
			// 关闭弹窗
			closePopup: function() {
				this.$refs.popup1.close();
				this.$refs.popup2.close();
				this.$refs.popup3.close();
				this.$refs.powerPopup.close();
			},
			//主动断开蓝牙连接
			disBleConnect() {
				app.closeBLEConnection()
			},
			// 连接蓝牙
			toConnectBluetooth() {
				let that = this;
				if (this.isClick) {
					this.ConnectBtnText = '连接中...';
					this.isClick = false;
					// 清空设备列表
					app.globalData.devices = [];
					app.closeBluetoothAdapter_connect();
					let timer = setTimeout(function() {
						console.log('延时。。。');
						if (!that.isMonitor) {
							console.log('延时。');
							that.ConnectBtnText = '连接头环';
							that.isClick = true;
						}
					}, 8000);
				} else {
					console.log('ccccc');
				}
			},
			//获取健康模型的数据
			getUserModel() {
				// 请求健康模型
				let that = this;
				let data = {
					userId: this.userId,
					action: 'getUserModel'
				};
				api.getUserModel(data).then(function(res) {
					console.log('请求健康模型 ', res.data);
					that.$store.commit('isBuildModel', res.data.success)
				}).catch(function(error) {
					console.log('get getUserModel fail', error);
				});
			},
			/**
			 *   监测部分 ...
			 */
			// 进入快速检测页面
			toFastMonitor: function() {
				// 监听 检测（监测）返回的是否弹窗的事件
				let that = this;
				uni.$once('alreadyPopup', function(data) {
					if (data) that.$refs.popup3.close();
				});
				// 设置只有蓝牙连接后才可以去检测
				if (this.isMonitor) {
					if (this.adorn == "未佩戴") {
						this.$toast('请检查头环佩戴情况')
						return;
					}
					store.commit('isLoopCheckConnectState', false)
					if (this.deviceVersion === '1.0.0') {
						store.commit('SET_regApi','/reg-data-center-service/public');
						console.log('V1.0');
						uni.navigateTo({
							url: 'fastMonitor/fastMonitor'
						});
					} else if(this.deviceVersion === '2.0.0'){
						store.commit('SET_regApi','/reg-data-center-service/public');
						console.log('V2.0');
						uni.navigateTo({
							url: 'fastMonitor/fastMonitorNew'
						});
					} else {
						console.log('V3.0');
						store.commit('SET_regApi','/reg-data-center-service/private/Reg2');
						uni.navigateTo({
							url: 'fastMonitor/fastMonitorNew'
						});
					}
				} else {
					this.$toast('蓝牙未连接', {
						icon: 'error'
					});
				}
			},
			toDeepMonitor() {
				let that = this;
				uni.$once('alreadyPopup', function(data) {
					if (data) that.$refs.popup3.close();
				});
				if (this.isMonitor) {
					if (this.adorn == "未佩戴") {
						this.$toast('请检查头环佩戴情况')
						return;
					}
					uni.navigateTo({
						url: 'deepMonitor/deepMonitor'
					});
				} else {
					this.$toast('蓝牙未连接', {
						icon: 'error'
					});
				}
			},
			// 历史报告
			toHistoryReport: function() {
				uni.navigateTo({
					url: 'historyReport/historyReport'
				});
			},
			// 消息处理
			DealMessage: function(buffer) {
        console.log('DealMessage',buffer)
				let that = this;
				let array = Array.prototype.slice.call(new Uint8Array(buffer));
				let CrcContent = array.slice(1, -3);
				let crc16 = util.crc16_false(CrcContent);
        if ( array[3] === 0x06) {
          console.log('power' + array[4]);
          this.power = array[4];
          if (array[3] <= 15) this.$refs.powerPopup.open('center');
        }

        if (array[0] === 0x68 && array[array.length - 1] === 0x16) {
					if (array[array.length - 3] === crc16[0] && array[array.length - 2] === crc16[1]) {
						//crc pass
            if (array[2] === 0x08 && array[3] === 0x07) {
							this.adorn = array[4] == 0x00 ? '已佩戴' : '未佩戴';
						} else if (array[2] === 0x0D && array[3] === 0x10) {
							this.deviceVersion = `${array[7]}.${array[8]}.${array[9]}`;
						} else if (array[2] === 0x17 && array[3] === 0x20) {
							let body = array.slice(4, 20);
							let sss = "";
							body.forEach((item) => {
								sss += item.toString(16)
							})
							this.getServiceInfo(this.$utils.hexToString(sss));
						}
					}
				}
			},
			// 获取服务信息
			getServiceInfo(id) {
				let that = this;
				let data = {
					userId: that.userId,
					action: 'getServiceInfo'
				};
				api.getServiceInfo(data)
					.then(async function(res) {
						console.log('res', res);
						if (res.data.code == 2000) {
							if (res.data.message == '该用户未绑定服务') {
								let erpToken = await app.getErpToken()
								if (erpToken) {
									that.getCardInfo(erpToken, id)
								}
							} else if (res.data.data.productId == '' || res.data.data.productId == null) {
								that.changeServiceProductId(id)

							} else if (res.data.data.productId !== id) {
								console.log('不相同');
								that.userDeviceIdError(id, res.data.data.productId)
							}
						}
					})
					.catch(function(error) {
						console.log('getServiceInfo fail', error);
					});
			},
			changeServiceProductId(id) {
				let that = this
				let data = {
					action: '',
					userId: this.userId,
					params: id
				}
				api.changeServiceProductId(data).then(function(res) {
					if (res.data.code == 2000) {}
				}).catch(function(err) {
					console.log('changeServiceProductId fail', err);
				})

			},
			bindService(cardId) {
				let that = this
				let data = {
					action: 'bindService',
					userId: this.userId,
					params: {
						cardId
					}
				}
				api.bindService(data).then(function(res) {
					if (res.data.code == 2000) {
						if (res.data.message == '该设备的服务账户绑定用户数量已满') {
							that.$toast('今日绑定用户数量已满', {
								icon: 'none'
							})
							return
						}
					} else {
						that.$toast('头环绑定失败，请联系客服人员', {
							icon: 'none',
							duration: 5000
						})
						app.closeBLEConnection()
						return
					}
				}).catch(function(err) {
					console.log('bindService fail', err);
				})
			},
			//上报用户 设备不符合的情况
			userDeviceIdError(realId, serviceDeviceId) {
				let that = this;
				let data = {
					userId: that.userId,
					action: 'report',
					params: {
						realId,
						serviceDeviceId
					}
				};
				api.userDeviceIdError(data).then(function(res) {
					console.log('userDeviceIdError res', res);
				}).catch(function(error) {
					console.log('userDeviceIdError fail', error);
				});
			},
			getCardInfo(erpToken, id) {
				let that = this
				uni.request({
					url: that.$config.HttpUrl + '/service-product-management/inner/productManagement',
					method: 'POST',
					header: {
						token: erpToken
					},
					data: {
						action: 'get',
						params: {
							id
						}
					},
					success(res) {
						if (res.data.success) {
							that.bindService(res.data.data.product.cardId)
						} else {
							that.$toast(res.data.message)
						}
					},
					fail(err) {
						console.log('productManagement fail', err);
					}
				})
			},
			// 图表区域禁止 触发底层滚动
			moveHandle(e) {
				// console.log('moveHandle',e);
			},
			getChartIndex(e) {
				if (e.currentIndex.index < 0) e.currentIndex.index = 0;
				this.getHistoryReport(this.choiceTrendData.reportId[e.currentIndex.index])
			},
			getHistoryReport(reportId) {
				let that = this;
				let data = {
					userId: this.$store.state.userInfo.currentUser.userId,
					params: {
						eqSearchKey: {
							reportId: [reportId]
						},
						orderDesc: 'createTime',
						currentPage: 1,
						pageSize: 1
					}
				};
				api.getHistoryReport(data).then(function(res) {
					console.log('请求历史数据 ', res);
					if (res.data.success) {
						let report = res.data.data.reportList[0]
						let ageAvg = (report.minVascularAge + report.maxVascularAge) / 2
						let userAge = that.$utils.getAge(that.$store.state.userBaseInfo.birthday);
						that.trendReport.bloodAge = ageAvg - userAge > 0 ? '+' + (ageAvg - userAge) : (ageAvg -
							userAge == 0 ? '±' + (ageAvg - userAge) : (ageAvg - userAge))
						that.trendReport.heartRate = report.heartBeat
						that.trendReport.bloodAdjust = report.adjustScore
						that.trendReport.bloodElasticity = report.hardScore
						that.trendReport.headhealth = report.brainHealthScore
					}
				}).catch(function(error) {
					console.log('get history Data fail', error);
				});
			},
			// 切换Tab Item
			changeItem(e) {
				// console.log('我是Tab');
				let item = e.detail.current;
				if (item == 0) {
					this.toDetection();
				} else if (item == 1) {
					this.toTrend();
					// 请求趋势数据
					this.getTrend();
					this.getUserInfo();
				}
			},
			// 监测页面  切换Tab
			toDetection: function() {
				this.swiperIndex = 0;
				// 恢复趋势数据
				this.trendData = [];
			},
			//数据说明页面
			toIntroductDetail: function() {
				uni.navigateTo({
					url: 'introductData/introductData'
				});
			},
			/**
			 * 趋势-------------------------------------------------------
			 */
			toTrend: function() {
				this.swiperIndex = 1;
				// 请求趋势数据
				// this.getTrend();
			},
			getTrend() {
				let that = this;
				let userId = this.userId;
				let data = {
					userId: userId,
					action: 'getTrend'
				};
				api.getTrend(data)
					.then(function(res) {
						console.log('getTrend success ', res);
						if (res.data.code == 2000) {
							if (res.data.data.trend.length == 0) {
								that.isHistoryData = false;
								that.$toast('您还没有监测', {
									icon: 'error'
								});
								return;
							}
							that.isHistoryData = true;
							that.trendData = res.data.data.trend
							// 默认选择30日的数据
							that.SelectDate(30);
						}
					})
					.catch(function(error) {
						console.log(' getTrend fail', error);
					});
			},
			// 获取用户信息 取出病史
			getUserInfo() {
				let that = this;
				let userId = this.userId;
				let data = {
					userId: userId,
					action: 'getUserInfo'
				};
				//调用接口请求个人信息
				api.getUserInfo(data)
					.then(function(res) {
						// console.log('getUserInfo::', res);
						if (res.data.code == 2000) {
							let Info = res.data.data;
							that.getKeyWord(Info.stroke, Info.hypertension, Info.highBloodHyperglycemia, Info
								.highBloodLipids, Info.heartDisease);
						}
					})
					.catch(function(error) {
						console.log('getUserInfo fail', error);
					});
			},
			// 提取病史关键词
			getKeyWord(isStroke, isHBPressure, isHyperglycemia, isHyperlipidemia, isHeartDisease) {
				let keyWord = '';
				if (isStroke) keyWord += '#中风史';
				if (isHBPressure) keyWord += '#高血压';
				if (isHyperglycemia) keyWord += '#高血糖';
				if (isHyperlipidemia) keyWord += '#高血脂';
				if (isHeartDisease) keyWord += '#心脏病';
				if (!isStroke && !isHBPressure && !isHyperglycemia && !isHyperlipidemia && !isHeartDisease) keyWord +=
					'#无病史';
				// 在此处获取一些建议
				this.getSuggest(keyWord);
			},
			/*  获取信息  整个页面的全部内容
			 *---生活建议   饮食建议  早餐 午餐 晚餐 菜谱 运动建议 ~~具体运动~~ 药膳
			 */
			getSuggest(keyWord) {
				console.log(keyWord);
				let that = this;
				let userId = this.userId;
				let data = {
					action: 'getAdviceOnRecuperation',
					params: {
						keyList: [{
								channelName: '生活建议',
								type: 'contents',
								count: 1,
								keyWord: keyWord
							},
							{
								channelName: '饮食建议',
								type: 'contents',
								count: 1,
								keyWord: keyWord
							},
							{
								channelName: '早餐',
								type: 'images',
								count: 2,
								keyWord: keyWord
							},
							{
								channelName: '午餐',
								type: 'images',
								count: 4,
								keyWord: keyWord
							},
							{
								channelName: '晚餐',
								type: 'images',
								count: 3,
								keyWord: keyWord
							},
							{
								channelName: '菜谱',
								type: 'contents',
								count: 2,
								keyWord: keyWord
							},
							{
								channelName: '运动建议',
								type: 'contents',
								count: 1,
								keyWord: keyWord
							},
							{
								channelName: '运动详情',
								type: 'contents',
								count: 2,
								keyWord: keyWord
							},
							{
								channelName: '药膳',
								type: 'contents',
								count: 1,
								keyWord: keyWord
							}
						]
					}
				};
				api.getAdviceOnRecuperation(data)
					.then(function(res) {
						console.log('getAdviceOlnRecuperation success', res);
						if (res.data.code == 2000) {
							that.lifeAdvice.description = res.data.data.生活建议[0].description;
							that.lifeAdvice.accessUrl = res.data.data.生活建议[0].accessUrl;

							that.dietAdvice.description = res.data.data.饮食建议[0].description;
							that.dietAdvice.accessUrl = res.data.data.饮食建议[0].accessUrl;

							that.sportAdvice.description = res.data.data.运动建议[0].description;
							that.sportAdvice.accessUrl = res.data.data.运动建议[0].accessUrl;
							// 早餐
							that.breakfast = res.data.data.早餐;
							that.lunch = res.data.data.午餐;
							that.dinner = res.data.data.晚餐;
							// 药膳
							that.tonicDiet.title = res.data.data.药膳[0].title;
							that.tonicDiet.accessUrl = res.data.data.药膳[0].accessUrl;
							// 菜谱
							that.menu = res.data.data.菜谱;
							// 运动详情
							that.sportDetail = res.data.data.运动详情;
						}
					})
					.catch(function(error) {
						console.log('getAdviceOnRecuperation fail', error);
					});
			},
			// 生活建议
			toLifeDetail() {
				let that = this;
				uni.navigateTo({
					url: '../square/contentDetail/contentDetail?url=' + that.lifeAdvice.accessUrl
				});
			},
			//饮食建议
			toDietDetail() {
				let that = this;
				uni.navigateTo({
					url: '../square/contentDetail/contentDetail?url=' + that.dietAdvice.accessUrl
				});
			},
			// 菜谱
			toMenuDetail(index) {
				let that = this;
				uni.navigateTo({
					url: '../square/contentDetail/contentDetail?url=' + that.menu[index].accessUrl
				});
			},
			// 运动建议
			toSportDetail() {
				let that = this;
				uni.navigateTo({
					url: '../square/contentDetail/contentDetail?url=' + that.sportAdvice.accessUrl
				});
			},
			// 运动详情 详细
			toSportCardDetail(index) {
				let that = this;
				uni.navigateTo({
					url: '../square/contentDetail/contentDetail?url=' + that.sportDetail[index].accessUrl
				});
			},
			// 药膳
			toTonicDietDetail() {
				let that = this;
				uni.navigateTo({
					url: '../square/contentDetail/contentDetail?url=' + that.tonicDiet.accessUrl
				});
			},
			/*
			 * 选择日期范围  :计算 当前日期前几天的 数据筛选
			 */
			SelectDate: function(days) {
				this.extractParameter(days);
				// 选择日期的数据
				switch (days) {
					case 7:
						this.changeBgColor();
						this.selectDateBtnBg1 = '#e5e5e5';
						break;
					case 15:
						this.changeBgColor();
						this.selectDateBtnBg2 = '#e5e5e5';
						break;
					case 30:
						this.changeBgColor();
						this.selectDateBtnBg3 = '#e5e5e5';
						break;
					case 60:
						this.changeBgColor();
						this.selectDateBtnBg4 = '#e5e5e5';
						break;
				}
				this.$forceUpdate();
			},
			// 赋值给图表 提取参数（次数、极值、平均值）
			extractParameter(days) {
				let choiceData = {
					Score: [],
					Time: [],
					reportId: []
				};
				let trend = JSON.parse(JSON.stringify(this.trendData))
				trend.forEach((item, index) => {
					if (util.Dayz(item.createTime.slice(0, 10)) <= days) {
						choiceData.Score.push(item.synScore);
						choiceData.Time.push(item.createTime.slice(5, 16));
						choiceData.reportId.push(item.reportId);
					}
				});
				this.choiceTrendData = choiceData
				// 绘图
				this.chartData.categories = choiceData.Time;
				this.chartData.series[0].data = choiceData.Score;
				if (choiceData.Time.length == 0) {
					this.healthyCount = 0;
					this.$forceUpdate();
					return;
				}
				this.healthyCount = choiceData.Score.length;
				// 刷新页面内容
				this.$forceUpdate();
			},
			//更改日期按钮背景颜色 全部初始化
			changeBgColor: function() {
				this.selectDateBtnBg1 = '';
				this.selectDateBtnBg2 = '';
				this.selectDateBtnBg3 = '';
				this.selectDateBtnBg4 = '';
			}
		}
	};
</script>

<style>
	@import url('../style/suggestStyle.css');

	page {
		background-color: #f5f5f5;
		width: 750rpx;
		height: 100%;
	}

	.test {
		width: 700rpx;
		height: 500rpx;
		background-color: #07C160;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 100vw;
		height: 100%;
	}

	.flex-c {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.flex-c-reverse {
		display: flex;
		flex-direction: column-reverse;
		align-items: center;
		justify-content: center;
	}

	.NetState {
		position: absolute;
		top: 35rpx;
		width: 686rpx;
		height: 48rpx;
	}

	.TabView {
		margin-top: 100rpx;
		/* margin-top: calc(var(--status-bar-height)); */
		margin-left: 34rpx;
		width: 290rpx;
		align-self: flex-start;
		display: flex;
		align-items: center;
	}

	.TabView_item {
		display: flex;
		flex-direction: column;
		align-items: center;
		/* justify-content: space-between; */
		margin-right: 40rpx;
	}

	.TabsLine1 {
		width: 62rpx;
		height: 10rpx;
		background: #0659c7;
		border-radius: 15px;
		margin-top: 24rpx;
		animation: lineStyle1 .3s linear 1;
	}

	@keyframes lineStyle1 {
		0% {
			width: 0rpx;
		}

		50% {
			width: 30rpx;
		}

		100% {
			width: 62rpx;
		}
	}

	.TabsLine2 {
		width: 0;
		height: 10rpx;
		background: #0659c7;
		border-radius: 15px;
		margin-top: 24rpx;
		animation: lineStyle2 .3s linear 1;
	}

	@keyframes lineStyle2 {
		0% {
			width: 62rpx;
		}

		50% {
			width: 30rpx;
		}

		100% {
			width: 0rpx;
		}
	}

	.swiperView {
		width: 750rpx;
		height: 100%;
		/* background-color: #1989FA; */
	}

	.Title1 {
		font-family: Source Han Sans SC;
		font-weight: bold;
		line-height: 27px;
		color: #0659c7;
		font-size: 54rpx;
		animation: fontStyle1 .3s linear 1;
	}

	@keyframes fontStyle1 {
		0% {
			font-size: 44rpx;
		}

		50% {
			font-size: 50rpx;
		}

		100% {
			font-size: 54rpx;
		}
	}

	.Title2 {
		font-family: Source Han Sans SC;
		font-weight: bold;
		line-height: 27px;
		color: #333333;
		font-size: 44rpx;
		animation: fontStyle2 .3s linear 1;
	}

	@keyframes fontStyle2 {
		0% {
			font-size: 54rpx;
		}

		50% {
			font-size: 50rpx;
		}

		100% {
			font-size: 44rpx;
		}
	}

	/* 监测页  自底向上布局 */
	.detectionPage {
		position: relative;
	}

	.titleStyle {
		font-size: 44rpx;
		font-family: Source Han Sans SC;
		font-weight: bold;
		color: #333333;
	}

	.Title1 {
		font-family: Source Han Sans SC;
		font-weight: bold;
		line-height: 27px;
	}

	.HeadBandImgView {
		/* position: absolute;
	top: 0; */
		width: 100%;
		height: calc(100% - 800rpx);
	}

	.HeadBandImg {
		/* width: 313rpx; */
		width: 40%;
		/* background-size: cover; */
		/* margin: 30rpx auto auto; */
	}

	.absoultView {
		/* position: absolute;
	bottom: 0; */
	}

	.DisplayArea {
		width: 750rpx;
		margin: 43rpx auto auto;
	}

	.ConnectBtn {
		width: 326rpx;
		height: 78rpx;
		border-radius: 50px;
		background-color: #0659c7;
	}

	.ConnectBtn text {
		font-size: 44rpx;
		font-family: Source Han Sans CN;
		font-weight: bold;
		color: #ffffff;
	}

	.DisplayArea_btn {
		width: 484rpx;
		height: 100rpx;
		border-radius: 50px;
		background-color: #0659c7;
	}

	.ConnectBtn {
		width: 484rpx;
		height: 100rpx;
	}

	.StatusBar {
		width: 643rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.StatusBar_item {
		height: 100rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
	}

	/* 未佩戴的显示 */
	.noAdorn {
		animation: blink 1s linear infinite;
	}

	@keyframes blink {
		0% {
			opacity: 1;
		}

		100% {
			opacity: 0;
		}
	}

	.StatusBar_item_Des {
		font-size: 32rpx;
		font-family: Source Han Sans CN;
		font-weight: bold;
		color: #333333;
	}

	.power {
		font-size: 38rpx;
		font-family: Roboto;
		font-weight: bold;
		color: #333333;
	}

	/* 卡片区域 */
	.cardView {
		width: 700px;
	}

	.card_img {
		width: 700rpx;
		height: 280rpxf;
		margin: 24rpx auto auto;
	}

	/* 趋势页样式 */
	.TendArea {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.chartArea {
		margin-top: 20rpx;
		background-color: #ffffff;
		width: 100vw;
	}

	.selectDateView {
		width: 702rpx;
		margin-top: 38rpx;

		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
	}

	.selectDateBtn {
		width: 170rpx;
		height: 60rpx;
		border-radius: 15px;

		font-size: 32rpx;
		font-family: Roboto;
		font-weight: normal;
		color: #000000;
	}

	/* 图表区域样式 */
	.charts-box {
		width: 100%;
		height: 300px;
	}

	.reportDataView {
		position: relative;
		margin-top: 45rpx;
		width: 700rpx;
		border-radius: 15rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
		background-color: #FFFFFF;
		padding: 20rpx 0;
	}

	.reportDataViewImg {
		position: absolute;
		top: 0;
		left: 0;
		width: 202rpx;
	}

	.reportDataView .line {
		margin: 20rpx;
		width: 652rpx;
		height: 2rpx;
		background-color: #DCDCDC;
	}

	.reportDataView_T {
		width: 650rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.reportData_top {
		/* display: flex;
			align-items: flex-end; */
	}

	.reportData_top text:nth-child(1) {
		font-size: 25rpx;
		color: #000000;
	}

	.reportData_top text:nth-child(2) {
		display: inline-block;
		margin: 0 5rpx 0 15rpx;
		font-size: 40rpx;
		font-style: italic;
		font-weight: bold;
		color: #000000;
	}

	.reportData_top text:nth-child(3) {
		font-size: 23rpx;
		color: #000000;
	}

	.reportDataItem {}

	.reportDataItem_name {
		font-size: 26rpx;
		font-weight: bold;
		color: #000000;
	}

	.reportDataItem_des {
		margin-top: 20rpx;
		width: 135rpx;
		height: 94rpx;
		background-color: #F7F7F7;
		border-radius: 15rpx;
		font-size: 36rpx;
		font-weight: bold;
		color: #000000;
	}

	.ml28 {
		margin-left: 28rpx;
	}

	.mt28 {
		margin-top: 28rpx;
	}

	.mt45 {
		margin-top: 45rpx;
	}

	/* 生活  饮食 等建议 */
	.LifeAdvice {
		width: 703rpx;
		height: 334rpx;
		border-radius: 15px;
		background-color: #ffffff;
	}

	.tipView {
		margin-top: 60rpx;
		display: flex;
		align-items: center;
		justify-content: flex-start;
	}

	.tipLine {
		width: 10rpx;
		height: 35rpx;
		background-color: #fbad15;
		border-radius: 15px;
	}

	.LifeAdvice_title {
		font-size: 40rpx;
		font-family: Source Han Sans CN;
		font-weight: bold;
		color: #000000;
	}

	.LifeAdvice_content {
		font-size: 32rpx;
		font-family: Source Han Sans CN;
		font-weight: normal;
		color: #333333;
	}

	/* 弹出层  */
	.popup_input_view {
		width: 620rpx;
		height: 500rpx;
		background-color: white;
		border-radius: 15px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
	}

	.popup1 {
		width: 620rpx;
		height: 750rpx;
		background-color: white;
		border-radius: 15px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
	}

	.icon_content {
		margin-top: 93rpx;
		width: 238rpx;
		height: 238rpx;
	}

	.popup1Content {
		margin-top: 20rpx;
		font-size: 52rpx;
		font-family: Source Han Sans CN;
		font-weight: normal;
		color: #333333;
	}

	.icon_close {
		width: 40rpx;
		height: 40rpx;
		position: absolute;
		top: 26rpx;
		right: 35rpx;
	}

	.popupBottomView {
		margin-bottom: 0rpx;
		width: 100%;
		height: 120rpx;
		border-radius: 0 0 15px 15px;
		background-color: #0659c7;
	}

	.popupBottomView text {
		font-size: 44rpx;
		font-family: Source Han Sans CN;
		font-weight: normal;
		color: #ffffff;
	}
</style>